package cn.est.serviceImpl;

import cn.est.config.AlipayConfig;
import cn.est.constants.Constants;
import cn.est.dto.AlipayBean;
import cn.est.exceptions.PayException;
import cn.est.pojo.MaintainOrder;
import cn.est.pojo.PayOrder;
import cn.est.service.AlipayService;
import cn.est.service.MaintainOrderService;
import cn.est.service.PayOrderService;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class AlipayServiceImpl  implements AlipayService {



    @Autowired
    AlipayConfig alipayConfig;



    @Autowired
    AlipayClient alipayClient;

    @Autowired
    PayOrderService payOrderService;

    @Autowired
    MaintainOrderService maintainOrderService;

    @Override
    public String pay(MaintainOrder maintainOrder) throws AlipayApiException {


        //1.获取初始化的alipayCient
        //2.封装alipay支付请求对象 AlipayTradePagePayRequest
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());

        //3.保存支付订单信息到数据库
        PayOrder payOrder =payOrderService.save(maintainOrder, Constants.Order.Channel.ALIPAY);


        //4.请求支付宝进行付款，并获取支付结果
        AlipayBean alipayBean =new AlipayBean();
        alipayBean.setOut_trade_no(payOrder.getPayNo());
        alipayBean.setTotal_amount(maintainOrder.getSubscription().toString());
        alipayBean.setSubject("维修订单支付");
        alipayBean.setProduct_code("FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
        System.out.println(JSON.toJSONString(alipayBean));
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;
    }

    @Override
    public int asynNotify(HttpServletRequest request) throws UnsupportedEncodingException, PayException {
            int succ=0;   //通知成功为1  通知失败为0

            //1.获取参数
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易状态
      //  String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        String trade_status="TRADE_SUCCESS";



        //商户appid
        String app_id = new String(request.getParameter("app_id").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易金额
        String total_amount= new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");


        //2.交易状态判断
        Map map =new HashMap();
        map.put("payNo",out_trade_no);

        List<PayOrder> payOrderList=payOrderService.getPayOrderListByMap(map);
        if(payOrderList.size()<=0){
            throw  new PayException("支付失败，没有此订单");
        }
        //3.支付信息校验
        if(!trade_status.equals("TRADE_SUCCESS")){
            throw  new PayException("阿里支付错误，状态码为："+trade_status);
        }

        //验签
        try {
            boolean verify_result=verify(request);
            if(verify_result){

                //4.订单相关的业务接口处理，订单表，支付订单表，订单流水表处理
               return maintainOrderService.finishPay(trade_no,out_trade_no,total_amount);

            }else{
                throw  new PayException("数据非法请求");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return 0;
    }



    private boolean verify(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new	 String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType()); //调用SDK验证签名
        return  signVerified;
    }


}
